package com.unytech.watersoil.service.security.impl;

import java.util.List;
import java.util.UUID;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.unytech.watersoil.common.Globals;
import com.unytech.watersoil.entity.security.Permission;
import com.unytech.watersoil.entity.security.PermissionGroup;
import com.unytech.watersoil.entity.security.User;
import com.unytech.watersoil.service.base.BaseDao;
import com.unytech.watersoil.service.security.UserService;
import com.unytech.watersoil.utils.MD5Util;

@Service @Transactional
public class UserServiceImpl extends BaseDao<User> implements UserService{
	
	String entityname = getEntityName(this.entityClass);
	
	public User loginVerify(String username, String pwd)
	{		
		MD5Util MD5 = new MD5Util();
		User user = null;
		if (username.equals(Globals.KINGNAME) && MD5.getMD5ofStr(pwd).equals(Globals.KINGPASSWORD))
		{
			user = new User();
			user.setUsername(username);
			user.setRealname("超级管理员");
			user.setState(1);
			
			return user;
		}
		
		//生成UUID
		System.out.println("生成的UUID："+UUID.randomUUID().toString());
		System.out.println("生成的UUID的长度："+UUID.randomUUID().toString().length());
		
		System.out.println("传过来的泛型类："+entityname);
		System.out.println("EM对象："+em);
		
		Query query = em.createQuery("select o from " + entityname + " o where o.username=?1 and o.password=?2");
		query.setParameter(1, username).setParameter(2, MD5.getMD5ofStr(pwd));
		//user = (User) query.getSingleResult();
		List<User> userlist = query.getResultList();
		System.out.println("查找之后返回的List："+userlist.size());
		//System.out.println("查找之后返回的用户："+user);
		return user;
	}

	public List<Permission> getUserPermission(User user)
	{		
		User curuser = em.find(User.class, user.getUid());

		PermissionGroup permgroup = curuser.getPermgroup();
		List<Permission> permission = (List<Permission>) permgroup.getPermissions();	
		
		return permission;
		
	}
}
